package com.lgj.demo0812.threads;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author lizy51
 * @date 2022-08-22 16:42
 */
public class Test01 {

    //创建资源
    private static volatile Object resourceA =new Object ();
    private static volatile Object resourceB =new Object() ;
    public static void main(String[] args) throws InterruptedException {
        //创建线程A
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取re sourceA 享资源 的监视器锁
                    synchronized (resourceA){
                        System.out.println("threadA get resourceA lock" );
                        synchronized (resourceB){
                            System.out.println("threadA get resourceB lock" );
                        }
                        //线程 阻塞，并择放获取到的 resourceA的锁
                        System.out.println ("threadA release resourceA lock" ) ;
                        resourceA.wait() ;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //创建线程B
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);

                    synchronized (resourceA){
                        System.out.println("threadB get resourceA lock");
                        System.out.println("threadB try get resourceB lock . . .");
                        synchronized (resourceB){
                            System.out.println ("threadB get resourceB lock") ;
                        // 线程B阻塞 ，并释放获取到的 resour eA的锁
                            System.out. println ("threadB release resourceA lock");
                            resourceA.wait() ;
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();

        System.out.println("over");
    }

}
